package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.Page;
import com.itheima.Service.SetmealService;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.config.AliOssProperties;
import com.itheima.pojo.Setmeal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Set;
import java.util.UUID;

@RestController("backendRestController")
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private AliOssProperties aliOssProperties;

    /**
     * 新增体验套餐
     * @param setmeal
     * @param checkgroupIds
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        try {
            log.info("新增套餐成功：{}",setmeal);
            setmealService.add(setmeal,checkgroupIds);

            // 获取图片名称
            String imgName = setmeal.getImg();
            if (imgName != null && !imgName.isEmpty()) {
                redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);
            }
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL,null);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS,null);
    }

    /**
     * 编辑
     * @param setmeal
     * @param checkGroupIds
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal, Integer[] checkGroupIds){
        try {
            log.info("修改套餐套餐成功：{}",setmeal);
            setmealService.edit(setmeal,checkGroupIds);

            // 获取图片名称
            String imgName = setmeal.getImg();
            if (imgName != null && !imgName.isEmpty()) {
                redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES,imgName);
            }

        } catch (Exception e) {
            return new Result(false,MessageConstant.EDIT_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_SETMEAL_SUCCESS,null);

    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public Result findById(String id){
        Setmeal setmeal = setmealService.findById(id);
        return new Result(true,"查询套餐成功",setmeal);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }

    /**
     * 图片上传
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile imgFile){
       try {

           // 获取原始文件名
            String orginalFilename = imgFile.getOriginalFilename();
            // 截取原始文件名后缀
           String extension = orginalFilename.substring(orginalFilename.lastIndexOf("."));
           // 构造新的文件名称
           String objectName = UUID.randomUUID().toString() + extension;
           // 文件请求路径
           String filePath = aliOssUtil.upload(imgFile.getBytes(),objectName);

           log.info("图片保存redis：{}",objectName);
           redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,objectName);

//           redisTemplate.opsForValue().set(objectName,filePath);
           return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,filePath);

       }catch (Exception e){
           log.error("文件上传失败{}",e);
       }
        return new Result(true,MessageConstant.PIC_UPLOAD_FAIL);
    }

    @Scheduled(cron = "0 0 * * * ?")// 一小时执行一次
    public void cleanUpGarbageImages(){
        // 获取所有上传的图片名称
        Set<String> uploadedImgs = redisTemplate.opsForSet().members(RedisConstant.SETMEAL_PIC_RESOURCES);
        // 获取保存在数据库中的图片名称
        Set<String> packageImgs = redisTemplate.opsForSet().members(RedisConstant.SETMEAL_PIC_DB_RESOURCES);

        if (uploadedImgs != null && packageImgs != null){
            // 计算辣鸡图片,存在于上传集合但是不存在于数据库集合的图片
            Set<String> garbageImgs = redisTemplate.opsForSet().difference(
                    RedisConstant.SETMEAL_PIC_RESOURCES,
                    RedisConstant.SETMEAL_PIC_DB_RESOURCES);

            OSS ossClient = null;
            try {
                ossClient = new OSSClientBuilder().build(
                        aliOssProperties.getEndpoint(),
                        aliOssProperties.getAccessKeyId(),
                        aliOssProperties.getAccessKeySecret()
                );
                for (String imageName : garbageImgs) {
                    try {
                        ossClient.deleteObject(aliOssProperties.getBucketName(), imageName);
                        log.info("Deleted image from OSS: {}", imageName);
                    } catch (Exception e) {
                        log.error("Failed to delete image from OSS: {}", imageName, e);
                    }
                }
            } catch (Exception e) {
                log.error("Failed to initialize OSS client", e);
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }

        }
    }
}
